import requests
import time
import re

class Danmu():
    def __init__(self):
        print("请输入要进的直播间id:")
        live_id = input()
        print("请输入保存文件的名字:")
        name = input()
        # 弹幕url
        self.url = 'https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory'
        # 请求头
        self.headers = {
            'Host':'api.live.bilibili.com',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0',
        }
        # 定义POST传递的参数
        self.data = {
            'roomid':live_id,
            'csrf_token':'',
            'csrf':'',
            'visit_id':'',
        }
        # 日志写对象
        self.log_file_write = open(name+'.log',mode='a',encoding='utf-8')
        # 读取日志
        log_file_read = open(name+'.log',mode='r',encoding='utf-8')
        self.log = log_file_read.readlines()
        
    def get_danmu(self):
        # 获取直播间弹幕
        html = requests.post(url=self.url,headers=self.headers,data=self.data).json()
        # 解析弹幕列表
        for content in html['data']['room']:
            if re.match(r'[【](.*?)',content['text']) !=None:
                # 获取昵称
                # nickname = content['nickname']
                # 获取发言
                text = content['text'].strip('【】')
                # 获取发言时间
                # timeline = content['timeline']
                # 记录发言
                # msg = timeline+' '+nickname+': '+text
                # msg = text
                # 判断对应消息是否存在于日志，如果和最后一条相同则打印并保存
                if text+'\n' not in self.log:
                    # 打印消息
                    print (text)
                    # 保存日志
                    self.log_file_write.write(text+'\n')
                    # 添加到日志列表
                    self.log.append(text+'\n')
                # 清空变量缓存
                # nickname = ''
                # text = ''
                # timeline = ''
                text = ''
            
        

# 创建bDanmu实例
bDanmu = Danmu()
while True:
    # 暂停0.5防止cpu占用过高
    time.sleep(0.3)
    # 获取弹幕
    bDanmu.get_danmu()